﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Security;
using System.Threading;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using System.IO;
using HIS.Utils;
using HISModels.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;


namespace HIS.Controllers.Schedule {
    public class Doctor : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private StringReader stringReader = null;
        private HISModels.Entities.DoctorSchedule doctorSchedule = null;
        private string doctorid = string.Empty;
        public string title { get; set; }


        #endregion

        public Doctor() {

        }

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public override void Index() {
            try {
                Data.Add("Pagetitle", "Doctor Schedule");
                RenderFile("Schedule\\schedulerdoctor.html");

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

      
        #region Bind to Table
        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void TableListDoctor() {
            try {
                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string doctorname = HttpContext.Current.Request["doctorname"];
                string code = HttpContext.Current.Request["code"];
                string specialist = HttpContext.Current.Request["specialist"];

                string ssearch = "specialist=" + specialist + ";doctorname=" + doctorname + ";code=" + code;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["doctorpaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Convert to JObject
                ///  
                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["aaData"];
                ///Modify it
                JArray aaDataModified = new JArray();
                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    oo["Id"] = KeanuMvc.Reference.CryptoString.Encrypt(oo["Id"].ToString());
                    oo["DoctorCode"] = (oo["DoctorCode"]).ToString();
                    oo["DoctorName"] = (oo["DoctorName"]).ToString();
                    oo["spec"] = (oo["spec"]).ToString();
                    aaDataModified.Add(oo);

                }
                o["aaData"] = aaDataModified;

                ///So serialize
                strJson = JsonConvert.SerializeObject(o);

                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        //bind data to table room
        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void TableListRooms() {
            try {
                ///Set Rest Url///
                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string starttime = HttpContext.Current.Request["start"];
                string endtime = HttpContext.Current.Request["end"];
                string day = HttpContext.Current.Request["day"];
                string name = HttpContext.Current.Request["roomname"];

                //int hourStart = 20;
                //int minuteStart = 00;
                int hourStart = Convert.ToInt32(HttpContext.Current.Request["start"].ToString().Split('-')[0]);
                int minuteStart = Convert.ToInt32(HttpContext.Current.Request["start"].ToString().Split('-')[1]);


                //int hourEnd =20;
                //int minuteEnd = 00;
                int hourEnd = Convert.ToInt32(HttpContext.Current.Request["end"].ToString().Split('-')[0]);
                int minuteEnd = Convert.ToInt32(HttpContext.Current.Request["end"].ToString().Split('-')[1]);

                var timestart = new TimeSpan(hourStart, minuteStart, 0);
                var timeend = new TimeSpan(hourEnd, minuteEnd, 0);
                int dayset = Convert.ToInt32(day);
                //Convert.ToInt32(HttpContext.Current.Request["ddDays"]);

                string ssearch = "starttime=" + timestart + ";endtime=" + timeend + ";dayset=" + dayset + ";name=" + name;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sSearch = ssearch;
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);

                string strUri = Global.ServiceUriDictionary["hospitalroom"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Convert to JObject
                ///
                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["aaData"];
                ///Modify it
                JArray aaDataModified = new JArray();
                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    oo["idroom"] = (oo["idroom"].ToString());
                    oo["roomname"] = (oo["roomname"]).ToString();

                    aaDataModified.Add(oo);
                }
                o["aaData"] = aaDataModified;

                ///So serialize
                strJson = JsonConvert.SerializeObject(o);

                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();

            }
        }

        //bind to datatable
        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void TableListOneWeek() {

            ///Set variables///
            try {
                ///Set Rest Url///
                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string doctorname = HttpContext.Current.Request["id"];

                string ssearch = "id=" + doctorname;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sSearch = ssearch;
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);

                string strUri = Global.ServiceUriDictionary["doctorschedulepagingcal"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Convert to JObject
                ///
                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["aaData"];
                ///Modify it
                JArray aaDataModified = new JArray();
                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    oo["DoctorName"] = (oo["DoctorName"].ToString());
                    oo["Location"] = (oo["Location"]).ToString();


                    string[] splitSunday = oo["Sunday"].ToString().Split(',');
                    string Sunday = string.Empty;
                    foreach (var item in splitSunday) {
                        Sunday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("0") + "\" style=\"text-decoration:none\">" + item + "</a>";

                    }
                    oo["Sunday"] = Sunday;

                    string[] splitMonday = oo["Monday"].ToString().Split(',');
                    string Monday = string.Empty;
                    foreach (var item in splitMonday) {
                        Monday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("1") + "\" style=\"text-decoration:none\">" + item.ToString() + "</a>";

                    }
                    oo["Monday"] = Monday;

                    string[] splitTuesday = oo["Tuesday"].ToString().Split(',');
                    string Tuesday = string.Empty;
                    foreach (var item in splitTuesday) {
                        Tuesday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("2") + "\" style=\"text-decoration:none\">" + item + "</a>";

                    }
                    oo["Tuesday"] = Tuesday;

                    string[] splitWednesday = oo["Wednesday"].ToString().Split(',');
                    string Wednesday = string.Empty;
                    foreach (var item in splitWednesday) {
                        Wednesday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("3") + "\" style=\"text-decoration:none\">" + item + "</a>";

                    }
                    oo["Wednesday"] = Wednesday;

                    string[] splitThursday = oo["Thursday"].ToString().Split(',');
                    string Thursday = string.Empty;
                    foreach (var item in splitThursday) {
                        Thursday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("4") + "\" style=\"text-decoration:none\">" + item + "</a>";

                    }
                    oo["Thursday"] = Thursday;

                    string[] splitFriday = oo["Friday"].ToString().Split(',');
                    string Friday = string.Empty;
                    foreach (var item in splitFriday) {
                        Friday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("5") + "\" style=\"text-decoration:none\">" + item + "</a>";

                    }
                    oo["Friday"] = Friday;

                    string[] splitSaturday = oo["Saturday"].ToString().Split(',');
                    string Saturday = string.Empty;
                    foreach (var item in splitFriday) {
                        Saturday += "<a href=\"/schedule/doctor/editschedule/?var=" + CryptoString.Encrypt(doctorname) + ";" + CryptoString.Encrypt(item.ToString().Replace(" ", "")) + ";" + CryptoString.Encrypt("6") + "\" style=\"text-decoration:none\">" + item + "</a>";
                    }
                    oo["Saturday"] = Saturday;

                    aaDataModified.Add(oo);
                }
                o["aaData"] = aaDataModified;

                ///So serialize
                strJson = JsonConvert.SerializeObject(o);

                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();

            }
        }

        #endregion

        #region Bind to Schedule Page

        //render to schedule function 
        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void Scheduler() {
            string strJson = string.Empty;
            string DoctorName = string.Empty;
            string GroupSpecialist = string.Empty;
            string SubSpecialist = string.Empty;
            try {
                Data.Add("Pagetitle", "Doctor Schedule");

                doctorid = KeanuMvc.Reference.CryptoString.Decrypt(HttpContext.Current.Request["id"].NullSafeToString());
                string strUri = Global.ServiceUriDictionary["doctor"] + doctorid + Global.ServiceUriDictionary["requestformat"];

                #region Render to another page

                stringReader = base.RestService.GetJson(strUri);

                ViewDataDoctor datadoctor = new ViewDataDoctor();

                datadoctor = JsonConvert.DeserializeObject<ViewDataDoctor>(stringReader.ReadToEnd());
             
                Data.Add("DoctorName", datadoctor.FullName);
                Data.Add("GroupSpecialist", datadoctor.GroupSpecialist);
                Data.Add("SubSpecialist", datadoctor.SubSpecialist);
                Data.Add("DoctorId", doctorid);
                ///So serialize
                strJson = JsonConvert.SerializeObject(datadoctor);

                stringReader.Dispose();
                base.RestService.Dispose();

                #endregion

                RenderFile("schedule\\schedulerdoctorcalendar.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        #endregion

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void SaveScheduleToService() {
            StringReader stringReader = null;
            string strUri = string.Empty;
          
            try {
                doctorSchedule = new DoctorSchedule() { StartScheduleTime = null, EndScheduleTime = null, AllDay = null };
                if (HttpContext.Current.Request.Form.Count > 0) {
                    ///(Get all request and set it to object with one condition, please ask your friend first!) All variable on view must be same as object property.
                    if (strNotification == string.Empty) {
                        doctorSchedule.PostHandler<HISModels.Entities.DoctorSchedule>();
                        int hourStart = Convert.ToInt32(HttpContext.Current.Request["StartTime"].Split(':')[0]);
                        int minuteStart = Convert.ToInt32(HttpContext.Current.Request["StartTime"].Split(':')[1]);

                        int hourEnd = Convert.ToInt32(HttpContext.Current.Request["EndTime"].Split(':')[0]);
                        int minuteEnd = Convert.ToInt32(HttpContext.Current.Request["EndTime"].Split(':')[1]);

                        doctorSchedule.StartScheduleTime = new TimeSpan(hourStart, minuteStart, 0);
                        doctorSchedule.EndScheduleTime = new TimeSpan(hourEnd, minuteEnd, 0);

                        doctorSchedule.DoctorId = Convert.ToInt32(HttpContext.Current.Request["HidenDoctorid"].ToString());
                        int byAppointment = Convert.ToInt32(HttpContext.Current.Request["AppoitmentId"].NullSafeToString());

                        if (byAppointment == 1) {
                            doctorSchedule.HospitalUnitRoomId = null;
                            doctorSchedule.AllDay = DateTime.Now;
                            doctorSchedule.HospitalUnitId = Convert.ToInt32(HttpContext.Current.Request["HospitalUnit"]);
                        } else {
                            doctorSchedule.HospitalUnitRoomId = Convert.ToInt32(HttpContext.Current.Request["HiddenRoomId"].ToString());
                        }
                        doctorSchedule.MinutePerSlot = Convert.ToInt32(HttpContext.Current.Request["MinuteSlot"]);
                        doctorSchedule.DaySet = Convert.ToInt32(HttpContext.Current.Request["DaySet"]);
                        doctorSchedule.RecordStatus = 1;

                        if (string.IsNullOrEmpty(HttpContext.Current.Request["ScheduleId"])) {
                            strUri = Global.ServiceUriDictionary["doctorschedule"] + Global.ServiceUriDictionary["requestformat"];
                            stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(doctorSchedule));
                        } else {
                            strUri = Global.ServiceUriDictionary["doctorschedule"] + Global.ServiceUriDictionary["requestformat"];
                            stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(doctorSchedule));
                        }
                        doctorSchedule = JsonConvert.DeserializeObject<DoctorSchedule>(stringReader.ReadToEnd());

                        if (doctorSchedule != null) {
                            strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        } else {
                            strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        }
                        strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                    }
                }
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                HttpContext.Current.Response.Write(strNotification);
            }
        }

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void RenderAvailableRoom() {
            try {

                Data.Add("StartTime", HttpContext.Current.Request["start"].Replace(':', '-'));
                Data.Add("EndTime", HttpContext.Current.Request["end"].Replace(':', '-'));
                Data.Add("Day", HttpContext.Current.Request["day"]);
                RenderFile("Schedule\\searchavailableroom.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void CreateScheduler() {
            ///Set variables///
            try {

                doctorid = CryptoString.Decrypt(HttpContext.Current.Request["id"].NullSafeToString());
            } catch {
            }
            try {
                string roomName = string.Empty;
                doctorSchedule = new DoctorSchedule() { StartScheduleTime = null, EndScheduleTime = null, AllDay = null };
                Utils.Helper.SetNullToEmptyString(doctorSchedule);
                Data["Pagetitle"] += " Add Doctor Scheduler";
                Data.Add("doctorSchedule", doctorSchedule);
                Data.Add("StartTime", doctorSchedule.StartScheduleTime.NullSafeToString());
                Data.Add("EndTime", doctorSchedule.EndScheduleTime.NullSafeToString());
                Data.Add("RoomName", roomName.NullSafeToString());
                Data.Add("doctorid", doctorid);
                Data.Add("ScheduleId", string.Empty);
                Data.Add("ddDays", Utils.Helper.GetDays("DaySet", null).NullSafeToString());
                Data.Add("ddSlot", Utils.Helper.GetMinutePerSlotDoctor("MinuteSlot", null).NullSafeToString());
                Data.Add("ddHospital", Utils.Helper.GetDropDownHospital("HospitalUnit","",false,base.RestService));
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                RenderFile("Schedule\\editschedulerdoctor.html");
                base.RestService.Dispose();
            }

        }

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void EditSchedule() {

            string StartTime = string.Empty;
            string EndTime = string.Empty;
            string hourStart = string.Empty;
            string minuteStart = string.Empty;

            string hourEnd = string.Empty;
            string minuteEnd = string.Empty;
            string RoomId = string.Empty;
            string RoomName = string.Empty;
            string Minuteperslot = string.Empty;
            string ScheduleId = string.Empty;
            ///Set variables///
            try {

                doctorid = CryptoString.Decrypt(HttpContext.Current.Request["var"].NullSafeToString().Split(';')[0].ToString());
                string time = CryptoString.Decrypt(HttpContext.Current.Request["var"].NullSafeToString().Split(';')[1]);
                string day = CryptoString.Decrypt(HttpContext.Current.Request["var"].NullSafeToString().Split(';')[2]);
 
                if (time == "ByAppointment") {
                    time = "00:00-00:00";
                }

                StartTime = time.Split('-')[0];
                EndTime = time.Split('-')[1];

                hourStart = StartTime.ToString().Split(':')[0];
                minuteStart = EndTime.ToString().Split(':')[1];

                hourEnd = EndTime.ToString().Split(':')[0];
                minuteEnd = EndTime.ToString().Split(':')[1];

                var timestart = hourStart + ":" + minuteStart;
                var timeend = hourEnd + ":" + minuteEnd;

                Data.Add("ddDays", Utils.Helper.GetDays("DaySet", day).NullSafeToString());
                Data.Add("Pagetitle", "Doctor Schedule");
                Data.Add("StartTime", timestart);
                Data.Add("EndTime", timeend);
                Data.Add("doctorid", doctorid);

                Data.Add("Encdoctorid", KeanuMvc.Reference.CryptoString.Encrypt(doctorid));
                Data.Add("cmd", "edit");

                string ssearch = "?starttime=" + timestart + ";endtime=" + timeend + ";dayset=" + day + ";doctorid=" + doctorid;
                string strUri = Global.ServiceUriDictionary["doctorschedulebycriteria"] + Global.ServiceUriDictionary["requestformat"];
                //Get Rest///
                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(ssearch));

                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["Detail"];
                ///Modify it
                JArray aaDataModified = new JArray();
                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    RoomId = oo["roomid"].ToString();
                    RoomName = (oo["roomname"]).ToString();
                    Minuteperslot = (oo["minuteperslot"]).ToString();
                    ScheduleId = (oo["doctorscheduleid"]).ToString();
                    aaDataModified.Add(oo);
                }
                o["aaData"] = aaDataModified;

                ///So serialize 
                Data.Add("ScheduleId", ScheduleId.NullSafeToString());
                Data.Add("RoomName", RoomName.NullSafeToString());
                Data.Add("HiddenRoomId", RoomId.NullSafeToString());
                Data.Add("ddSlot", Utils.Helper.GetMinutePerSlotDoctor("MinuteSlot", Minuteperslot).NullSafeToString());
                Data.Add("ddHospital", Utils.Helper.GetDropDownHospital("HospitalUnit", "", false, base.RestService));
                Data.Add("Actionform", Data["rooturl"] + "/frontoffice/doctorscheduler/savescheduletoservice/?id=$doctorid");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                RenderFile("Schedule\\editschedulerdoctor.html");
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "scheduler-manageschedule")]  
        public void DeleteSchedule() {

            int id = 0;
            string  json = string.Empty;
            try {

                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                return;
            }
            try {
                doctorSchedule = new HISModels.Entities.DoctorSchedule();
                string strUri = Global.ServiceUriDictionary["doctorschedule"] + Global.ServiceUriDictionary["requestformat"];

                StringReader strReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                doctorSchedule = JsonConvert.DeserializeObject<DoctorSchedule>(strReader.ReadToEnd());

                if (doctorSchedule != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }
                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

    }
}